package com.zyb.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

//自定义登录拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //业务逻辑实现
        String token = request.getHeader("Token");
        if(token == null){
            setErrorMsg(response);
            return false;
        }
        //查看时间是否为空
        Object obj = redisTemplate.opsForValue().get(token);
        if(obj == null){
            setErrorMsg(response);
            return false;
        }
        //刷新token时间
        redisTemplate.opsForValue().set(token,0,30, TimeUnit.MINUTES);

        return true;
    }

    private void setErrorMsg(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"msg\":\"noLogin\"}");
        writer.close();
    }
}
